package com.rongke.web.shiro;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.model.Admin;
import com.rongke.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * 管理员验证
 */
@Transactional
public class AdminPasswordRealm extends AuthorizingRealm{
	@Autowired
	private AdminService adminService;
	
	/**
	 * 为当前登录的用户授予权限
	 */
	@Override
	public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//String phone = (String)principals.getPrimaryPrincipal();
		//获取当前登录的用户名
		String currentUsername = (String)super.getAvailablePrincipal(principals);
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		try{

           System.out.print(currentUsername);

		}catch(Exception e){
			e.printStackTrace();
		}
		return authorizationInfo;
	}

	/**
	 * 验证当前登录的用户
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName = (String)token.getPrincipal();
		Subject currentUser = SecurityUtils.getSubject();
		Session session=currentUser.getSession();
		session.setAttribute("loginName"+userName,userName);
		String sessionId=session.getId().toString();
		EntityWrapper<Admin> ew =new EntityWrapper<>();
		ew.eq("login_name",userName);
		Admin admin = adminService.selectOne(ew);
		if(admin != null){
			AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(admin.getLoginName(), admin.getPassword(),this.getName());
			return authcInfo;
		}else{
			return null;
		}
	}
}	
